<template>
  <view class="room-model-manage-container">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">房间模式管理</text>
      <text class="page-subtitle">管理房间模型配置</text>
    </view>
    
    <!-- 操作栏 -->
    <view class="action-bar">
      <button class="create-btn" @click="showCreateModal">创建模式</button>
    
    </view>
    
    <!-- 模式列表 -->
    <view class="model-list-section">
      <view v-if="loading" class="loading-container">
        <view class="loading-spinner"></view>
        <text>加载中...</text>
      </view>
      
      <view v-else-if="modelList.length === 0" class="empty-state">
        <text>暂无房间模式</text>
      </view>
      
      <view v-else class="model-list">
        <view 
          class="model-item" 
          v-for="model in modelList" 
          :key="model.id"
        >
          <view class="model-header">
            <text class="model-id">ID: {{ model.id }}</text>
            <view class="model-actions">
              <button class="edit-btn" @click="editModel(model)">编辑</button>
              <button class="delete-btn" @click="deleteModel(model)">删除</button>
            </view>
          </view>
          
          <view class="model-content">
            <view class="model-row">
              <text class="model-label">模式名称:</text>
              <text class="model-value">{{ model.matchRoomModelName || '未设置' }}</text>
            </view>
            <view class="model-row">
              <text class="model-label">起点:</text>
              <text class="model-value">{{ model.startPoint }}</text>
            </view>
            <view class="model-row">
              <text class="model-label">终点:</text>
              <text class="model-value">{{ model.endPoint }}</text>
            </view>
            <view class="model-row">
              <text class="model-label">准备时间:</text>
              <text class="model-value">{{ formatTime(model.prepareTime) }}</text>
            </view>
            <view class="model-row">
              <text class="model-label">限制时间:</text>
              <text class="model-value">{{ formatTime(model.limitTime) }}</text>
            </view>
            <view class="model-row">
              <text class="model-label">排序:</text>
              <text class="model-value">{{ model.sort }}</text>
            </view>
            <view class="model-row">
              <text class="model-label">计分模式:</text>
              <text class="model-value">{{ getScoreModelText(model.scoreModel) }}</text>
            </view>
            <view class="model-row">
              <text class="model-label">对战模式:</text>
              <text class="model-value">{{ getBattleModelText(model.battleModel) }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 创建/编辑模态框 -->
    <view class="modal-overlay" v-if="showModal" @click="closeModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">{{ isEdit ? '编辑模式' : '创建模式' }}</text>
          <button class="close-btn" @click="closeModal">×</button>
        </view>
        
        <view class="modal-body">
          <view class="form-item">
            <text class="form-label">模式名称</text>
            <input 
              class="form-input" 
              v-model="formData.matchRoomModelName" 
              placeholder="请输入模式名称"
              maxlength="100"
            />
          </view>
          
          <view class="form-item">
            <text class="form-label">起点标识 *</text>
            <input 
              class="form-input" 
              v-model="formData.startPoint" 
              placeholder="请输入起点标识"
              maxlength="50"
            />
          </view>
          
          <view class="form-item">
            <text class="form-label">终点标识 *</text>
            <input 
              class="form-input" 
              v-model="formData.endPoint" 
              placeholder="请输入终点标识"
              maxlength="50"
            />
          </view>
          
          <view class="form-item">
            <text class="form-label">准备时间(毫秒) *</text>
            <input 
              class="form-input" 
              v-model="formData.prepareTime" 
              type="number"
              placeholder="请输入准备时间"
            />
          </view>
          
          <view class="form-item">
            <text class="form-label">限制时间(毫秒) *</text>
            <input 
              class="form-input" 
              v-model="formData.limitTime" 
              type="number"
              placeholder="请输入限制时间"
            />
          </view>
          
          <view class="form-item">
            <text class="form-label">排序</text>
            <input 
              class="form-input" 
              v-model="formData.sort" 
              type="number"
              placeholder="请输入排序值"
            />
          </view>
          
          <view class="form-item">
            <text class="form-label">计分模式</text>
            <view class="form-picker" @click="openScoreModelPicker">
              <view class="picker-text">{{ scoreModelOptions[scoreModelIndex] || '请选择计分模式' }}</view>
              <view class="picker-arrow">▼</view>
            </view>
          </view>
          
          <view class="form-item">
            <text class="form-label">对战模式</text>
            <view class="form-picker" @click="openBattleModelPicker">
              <view class="picker-text">{{ battleModelOptions[battleModelIndex] || '请选择对战模式' }}</view>
              <view class="picker-arrow">▼</view>
            </view>
          </view>
        </view>
        
        <view class="modal-footer">
          <button class="cancel-btn" @click="closeModal">取消</button>
          <button class="submit-btn" @click="submitForm" :disabled="submitting">
            {{ submitting ? '提交中...' : (isEdit ? '更新' : '创建') }}
          </button>
        </view>
      </view>
    </view>
    
    <!-- 计分模式选择模态框 -->
    <view class="modal-overlay" v-if="showScoreModelPicker" @click="closeScoreModelPicker">
      <view class="picker-modal-content" @click.stop>
        <view class="picker-modal-header">
          <text class="picker-modal-title">选择计分模式</text>
          <button class="close-btn" @click="closeScoreModelPicker">×</button>
        </view>
        <view class="picker-modal-body">
          <view 
            class="picker-option" 
            v-for="(option, index) in scoreModelOptions" 
            :key="index"
            @click="selectScoreModel(index)"
            :class="{ 'selected': scoreModelIndex === index }"
          >
            <text class="option-text">{{ option }}</text>
            <view class="option-check" v-if="scoreModelIndex === index">✓</view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 对战模式选择模态框 -->
    <view class="modal-overlay" v-if="showBattleModelPicker" @click="closeBattleModelPicker">
      <view class="picker-modal-content" @click.stop>
        <view class="picker-modal-header">
          <text class="picker-modal-title">选择对战模式</text>
          <button class="close-btn" @click="closeBattleModelPicker">×</button>
        </view>
        <view class="picker-modal-body">
          <view 
            class="picker-option" 
            v-for="(option, index) in battleModelOptions" 
            :key="index"
            @click="selectBattleModel(index)"
            :class="{ 'selected': battleModelIndex === index }"
          >
            <text class="option-text">{{ option }}</text>
            <view class="option-check" v-if="battleModelIndex === index">✓</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { MatchRoomModelAPI } from '@/api/battle.js'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const showModal = ref(false)
const isEdit = ref(false)
const searchKeyword = ref('')
const modelList = ref([])

// 选择器相关数据
const showScoreModelPicker = ref(false)
const showBattleModelPicker = ref(false)

// 表单数据
const formData = ref({
  matchRoomModelId: '',
  matchRoomModelName: '',
  startPoint: '',
  endPoint: '',
  prepareTime: 5000,
  limitTime: 30000,
  sort: 1,
  scoreModel: 1,
  battleModel: 1
})

// 选择器索引
const scoreModelIndex = ref(1)
const battleModelIndex = ref(1)

// 选项数据
const scoreModelOptions = [
  '不记分', '时间短', '时间长', '距离短', '距离长', 
  '得分少', '得分多', '步数短', '步数长'
]
const battleModelOptions = ['接力', '单回合', '多回合']

// 获取选项文本
const getScoreModelText = (type) => scoreModelOptions[type] || '未知'
const getBattleModelText = (type) => battleModelOptions[type] || '未知'

// 格式化时间显示
const formatTime = (milliseconds) => {
  if (!milliseconds) return '未设置'
  const seconds = Math.floor(milliseconds / 1000)
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  
  if (minutes > 0) {
    return `${minutes}分${remainingSeconds}秒`
  } else {
    return `${remainingSeconds}秒`
  }
}

// 加载模式列表
const loadModelList = async () => {
  loading.value = true
  try {
    const result = await MatchRoomModelAPI.page({
      pageNum: 0,
      pageSize: 100
    })
    
    console.log('API返回的完整结果:', result)
    
    if (result.code === 0 && result.data) {
      const list = result.data.list || result.data || []
      console.log('解析后的列表数据:', list)
      if (list.length > 0) {
        console.log('第一个项目的结构:', list[0])
      }
      modelList.value = list
    } else {
      modelList.value = []
      throw new Error(result.msg || '获取模式列表失败')
    }
  } catch (error) {
    console.error('获取模式列表失败:', error)
    uni.showToast({
      title: error.message || '获取模式列表失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 搜索功能
const onSearch = () => {
  // 这里可以实现本地搜索或重新请求API
  console.log('搜索关键词:', searchKeyword.value)
}

// 显示创建模态框
const showCreateModal = () => {
  isEdit.value = false
  resetForm()
  showModal.value = true
}

// 编辑模式
const editModel = (model) => {
  isEdit.value = true
  
  // 确保正确设置所有字段，特别是matchRoomModelId
  formData.value = {
    matchRoomModelId: model.id || model.matchRoomModelId, // 确保设置ID字段
    matchRoomModelName: model.matchRoomModelName || '',
    startPoint: model.startPoint || '',
    endPoint: model.endPoint || '',
    prepareTime: model.prepareTime || 5000,
    limitTime: model.limitTime || 30000,
    sort: model.sort || 1,
    scoreModel: model.scoreModel || 1,
    battleModel: model.battleModel || 1
  }
  
  // 设置选择器索引
  scoreModelIndex.value = model.scoreModel || 1
  battleModelIndex.value = model.battleModel || 1
  
  console.log('编辑模式数据:', formData.value)
  showModal.value = true
}

// 删除模式
const deleteModel = async (model) => {
  const modelId = model.id || model.matchRoomModelId
  uni.showModal({
    title: '确认删除',
    content: `确定要删除模式 ${modelId} 吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await MatchRoomModelAPI.remove({
            matchRoomModelId: modelId
          })
          
          if (result.code === 0) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
            loadModelList()
          } else {
            throw new Error(result.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除模式失败:', error)
          uni.showToast({
            title: error.message || '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 关闭模态框
const closeModal = () => {
  showModal.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  formData.value = {
    matchRoomModelId: '',
    matchRoomModelName: '',
    startPoint: '',
    endPoint: '',
    prepareTime: 5000,
    limitTime: 30000,
    sort: 1,
    scoreModel: 1,
    battleModel: 1
  }
  
  scoreModelIndex.value = 1
  battleModelIndex.value = 1
}

// 打开计分模式选择模态框
const openScoreModelPicker = () => {
  showScoreModelPicker.value = true
}

// 打开对战模式选择模态框
const openBattleModelPicker = () => {
  showBattleModelPicker.value = true
}

// 关闭计分模式选择模态框
const closeScoreModelPicker = () => {
  showScoreModelPicker.value = false
}

// 关闭对战模式选择模态框
const closeBattleModelPicker = () => {
  showBattleModelPicker.value = false
}

// 选择计分模式
const selectScoreModel = (index) => {
  scoreModelIndex.value = index
  formData.value.scoreModel = index
  closeScoreModelPicker()
}

// 选择对战模式
const selectBattleModel = (index) => {
  battleModelIndex.value = index
  formData.value.battleModel = index
  closeBattleModelPicker()
}

// 提交表单
const submitForm = async () => {
  // 表单验证
  if (!formData.value.startPoint.trim()) {
    uni.showToast({
      title: '请输入起点标识',
      icon: 'none'
    })
    return
  }
  
  if (!formData.value.endPoint.trim()) {
    uni.showToast({
      title: '请输入终点标识',
      icon: 'none'
    })
    return
  }
  
  if (formData.value.startPoint === formData.value.endPoint) {
    uni.showToast({
      title: '起点和终点不能相同',
      icon: 'none'
    })
    return
  }
  
  if (!formData.value.prepareTime || formData.value.prepareTime <= 0) {
    uni.showToast({
      title: '请输入有效的准备时间',
      icon: 'none'
    })
    return
  }
  
  if (!formData.value.limitTime || formData.value.limitTime <= 0) {
    uni.showToast({
      title: '请输入有效的限制时间',
      icon: 'none'
    })
    return
  }
  
  if (formData.value.prepareTime >= formData.value.limitTime) {
    uni.showToast({
      title: '准备时间必须小于限制时间',
      icon: 'none'
    })
    return
  }
  
  // 编辑模式下的额外验证
  if (isEdit.value && !formData.value.matchRoomModelId) {
    uni.showToast({
      title: '缺少房间模型ID',
      icon: 'none'
    })
    return
  }
  
  submitting.value = true
  try {
    const api = isEdit.value ? MatchRoomModelAPI.edit : MatchRoomModelAPI.create
    const submitData = { ...formData.value }
    
    console.log('提交数据:', submitData)
    console.log('是否为编辑模式:', isEdit.value)
    
    const result = await api(submitData)
    
    console.log('API返回结果:', result)
    
    if (result.code === 0) {
      uni.showToast({
        title: isEdit.value ? '更新成功' : '创建成功',
        icon: 'success'
      })
      closeModal()
      loadModelList()
    } else {
      throw new Error(result.msg || (isEdit.value ? '更新失败' : '创建失败'))
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    uni.showToast({
      title: error.message || (isEdit.value ? '更新失败' : '创建失败'),
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  loadModelList()
})
</script>

<style lang="scss" scoped>
.room-model-manage-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx;
}

.page-header {
  text-align: center;
  margin-bottom: 60rpx;
  
  .page-title {
    display: block;
    font-size: 48rpx;
    font-weight: bold;
    color: #fff;
    margin-bottom: 20rpx;
    text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
  }
  
  .page-subtitle {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.8);
  }
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
  
  .create-btn {
    height: 60rpx;
    padding: 0 30rpx;
    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
    border: none;
    border-radius: 12rpx;
    color: #fff;
    font-size: 26rpx;
    font-weight: bold;
  }
  
  .search-box {
    flex: 1;
    margin-left: 20rpx;
    
    .search-input {
      width: 100%;
      height: 60rpx;
      background: rgba(255, 255, 255, 0.9);
      border: none;
      border-radius: 12rpx;
      padding: 0 20rpx;
      font-size: 26rpx;
    }
  }
}

.model-list-section {
  .loading-container, .empty-state {
    text-align: center;
    color: #fff;
    padding: 50rpx;
  }
  
  .model-list {
    .model-item {
      background: rgba(255, 255, 255, 0.95);
      border-radius: 20rpx;
      padding: 30rpx;
      margin-bottom: 20rpx;
      box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);
      
      .model-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20rpx;
        
        .model-id {
          font-size: 28rpx;
          font-weight: bold;
          color: #333;
        }
        
        .model-actions {
          display: flex;
          gap: 10rpx;
          
          .edit-btn, .delete-btn {
            height: 50rpx;
            padding: 0 20rpx;
            border: none;
            border-radius: 8rpx;
            font-size: 24rpx;
            
            &.edit-btn {
              background: #007bff;
              color: #fff;
            }
            
            &.delete-btn {
              background: #dc3545;
              color: #fff;
            }
          }
        }
      }
      
      .model-content {
        .model-row {
          display: flex;
          margin-bottom: 10rpx;
          font-size: 26rpx;
          
          .model-label {
            width: 160rpx;
            color: #666;
          }
          
          .model-value {
            flex: 1;
            color: #333;
          }
        }
      }
    }
  }
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  
  .modal-content {
    width: 90%;
    max-height: 80%;
    background: #fff;
    border-radius: 20rpx;
    overflow: hidden;
    
    .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      border-bottom: 2rpx solid #eee;
      
      .modal-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .close-btn {
        width: 60rpx;
        height: 60rpx;
        border: none;
        background: none;
        font-size: 40rpx;
        color: #999;
      }
    }
    
    .modal-body {
      padding: 30rpx;
      max-height: 60vh;
      overflow-y: auto;
      
      .form-item {
        margin-bottom: 30rpx;
        
        .form-label {
          display: block;
          font-size: 28rpx;
          color: #333;
          margin-bottom: 15rpx;
          font-weight: bold;
        }
        
        .form-input {
          width: 100%;
          height: 80rpx;
          border: 2rpx solid #eee;
          border-radius: 12rpx;
          padding: 0 20rpx;
          font-size: 28rpx;
          background: #fff;
          box-sizing: border-box;
        }
        
        .form-picker {
          width: 100%;
          height: 80rpx;
          border: 2rpx solid #eee;
          border-radius: 12rpx;
          padding: 0 20rpx;
          background: #fff;
          display: flex;
          align-items: center;
          justify-content: space-between;
          box-sizing: border-box;
          cursor: pointer;
          
          .picker-text {
            font-size: 28rpx;
            color: #333;
          }
          
          .picker-arrow {
            font-size: 24rpx;
            color: #999;
          }
        }
      }
    }
    
    .modal-footer {
      display: flex;
      gap: 20rpx;
      padding: 30rpx;
      border-top: 2rpx solid #eee;
      
      .cancel-btn, .submit-btn {
        flex: 1;
        height: 80rpx;
        border: none;
        border-radius: 12rpx;
        font-size: 28rpx;
        font-weight: bold;
        
        &.cancel-btn {
          background: #f8f9fa;
          color: #666;
          border: 2rpx solid #eee;
        }
        
        &.submit-btn {
          background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
          color: #fff;
          
          &:disabled {
            opacity: 0.6;
          }
        }
      }
    }
  }
}

// 选择器模态框样式
.picker-modal-content {
  width: 80%;
  max-height: 70%;
  background: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  
  .picker-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 2rpx solid #eee;
    
    .picker-modal-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .close-btn {
      width: 60rpx;
      height: 60rpx;
      border: none;
      background: none;
      font-size: 40rpx;
      color: #999;
    }
  }
  
  .picker-modal-body {
    max-height: 50vh;
    overflow-y: auto;
    
    .picker-option {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      border-bottom: 1rpx solid #f5f5f5;
      cursor: pointer;
      transition: background-color 0.3s ease;
      
      &:hover {
        background-color: #f8f9fa;
      }
      
      &.selected {
        background-color: #e3f2fd;
        border-left: 4rpx solid #2196f3;
      }
      
      .option-text {
        font-size: 28rpx;
        color: #333;
      }
      
      .option-check {
        font-size: 32rpx;
        color: #2196f3;
        font-weight: bold;
      }
    }
  }
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #f3f3f3;
  border-top: 4rpx solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style> 